package com.example.login.controller;

import com.example.common.constant.SMSConstant;
import com.example.common.domain.Result;
import com.example.common.exception.CaptchaException;
import com.example.common.exception.PhoneAlreadyRegisteredException;
import com.example.login.domain.dto.EmployeeRegisterDTO;
import com.example.login.service.EmployeeAuthService;
import com.example.common.constant.MessageConstant;
import com.example.login.utils.SMSUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Tag(name="注册接口相关")
@RestController
@RequestMapping("/register/employee")
@RequiredArgsConstructor
@Slf4j
public class RegisteController {
   private final EmployeeAuthService employeeService;
   private final SMSUtil smsUtil;
   private final RedisTemplate<String,Object> redisTemplate;

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("/sendCaptcha")
    @Operation(summary ="发送验证码")
    public Result register(@NotBlank(message = "手机号不能为null、空字符串和空白串")
                           @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式错误")
                           String phone) {
        log.info("手机号码：{}", phone);
        Long count = redisTemplate.boundValueOps(SMSConstant.SMS_COUNT + phone).increment(1);
        // 10分钟内连续发送3次短信，则发送频繁
        if (count > 3) {
            log.info("验证码发送频繁,超过了限定的次数");
            // 设置10分钟的过期时间
            redisTemplate.boundValueOps(SMSConstant.SMS_COUNT + phone).expire(10, TimeUnit.MINUTES);
            throw new CaptchaException(MessageConstant.CAPTCHA_FREQUENT);
        }
        // 生成验证码
        String smsCode = smsUtil.getSMSCode();
        log.info("验证码：{}", smsCode);
        if (count == 1) {
            redisTemplate.expire(SMSConstant.SMS_COUNT + phone, SMSConstant.SMS_COUNT_EXPIRE_TIME, TimeUnit.SECONDS);
        }
        redisTemplate.opsForValue().set(SMSConstant.SMS_PHONE + phone, smsCode, SMSConstant.SMS_EXPIRE_TIME, TimeUnit.SECONDS);

        // 2. 发送验证码
        // smsUtil.sentCaptcha(phone, smsCode);

        return Result.success("验证码发送成功");
    }

    @PostMapping
    @Operation(summary ="员工注册")
    public Result register(@Validated @RequestBody EmployeeRegisterDTO employeeRegisterDTO) {
        log.info("员工注册,注册信息为：{}", employeeRegisterDTO);
        // 检查手机号是否已被注册
        Boolean isPhoneAvailable = employeeService.checkPhone(employeeRegisterDTO.getPhone());
        if (!isPhoneAvailable) {
            // PHONE_ALREADY_REGISTERED:手机号已注册
            throw new PhoneAlreadyRegisteredException(MessageConstant.PHONE_ALREADY_REGISTERED);
        }
        employeeService.register(employeeRegisterDTO);
        return Result.success("注册成功");
    }


}
